<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\Session;
use think\Db;
use app\index\service\SellerService;

class Seller extends Base{
	 public  function _initialize(){
	 	$this->get_session();
		$this->heade();
	 }

    //放单中心首页
    public function index()
    {
     $aggregate = $this->Summary();
	 $this->assign('aggregate',$aggregate);
     return $this->fetch();
    }

	   //放单人我的商品状态汇总
	  public function Summary(){
	   $date = Session::get('date');
	   $uid = $date['id'];
	   $whole = Db::table('think_goods')->where('uid','EQ',$uid)->count('*');//全部商品
	   $examine = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ',1)->where('end_time','>',time())->count('*');//审核中
	   $line = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ',2)->where('sale_time','<',time())->where('end_time','>',time())->count('*');//在线商品
	   $Invalid = Db::table('think_goods')->where('uid = '.$uid.' AND (status = 3 OR status = 4 OR (end_time < '.time().'))')->count('*');//无效商品
	   $booking = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ',2)->where('sale_time','>',time())->where('end_time','>',time())->count('*');//预售商品
	   $refuse = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ','3')->whereTime('sh_time','today')->count('*');//今日被拒商品
	   $aggregate['whole']=$whole;
	   $aggregate['examine']=$examine;
	   $aggregate['line']=$line;
	   $aggregate['Invalid']=$Invalid;
	   $aggregate['booking']=$booking;
	   $aggregate['refuse']=$refuse;
	   return $aggregate;

	  }

	//放单人我的商品//分类型
	public function zxGoods(){
	     $date = Session::get('date');
	     $uid = $date['id'];
		 $ip = input('ip');
		if($ip==0){
		$arry = Db::table('think_goods')->where('uid','EQ',$uid)->paginate(5,false,['query'=>input()]);
		}else if($ip==1){
			$arry = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ',2)->where('sale_time','<',time())->where('end_time','>',time())->paginate(5,false,['query'=>input()]);
		}else if($ip==2){
		  $arry = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ',1)->where('end_time','>',time())->paginate(5,false,['query'=>input()]);
		}else if($ip==3){
		  $arry = Db::table('think_goods')->where('uid = '.$uid.' AND (status = 3 OR status = 4 OR (end_time < '.time().'))')->paginate(5,false,['query'=>input()]);
		}else if($ip==4){
		  $arry = Db::table('think_goods')->where('uid','EQ',$uid)->where('sale_time','>',time())->where('status','EQ',2)->where('end_time','>',time())->paginate(5,false,['query'=>input()]);
		}else if($ip==5){
		 $keywords=input('keywords');
		 $arry = Db::table('think_goods')->where('sp_id','EQ',$keywords)->paginate(5,false,['query'=>input()]);
		}else if($ip==6){
		 $arry = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ','3')->whereTime('sh_time','today')->paginate(5,false,['query'=>input()]);
		}
		$aggregate = $this->Summary();
	    $this->assign('aggregate',$aggregate);
	    $this->assign('arry',$arry);
		return $this->fetch('mygoods');
	}

	  //商品下架
	  public function  sp_xj(){
	  	$id = input('id');
		$res = Db::table('think_goods')->where('id','EQ',$id)->update(['status'=>4]);
		if($res){
			$res_new['code'] = 1;
			$res_new['msg']='下架成功';
		}else{
			$res_new['code'] = 0;
			$res_new['msg']='下架失败，请稍后再试';
		}
		return $res_new;
	  }

     //商品修改渲染模板
	  public function updateseller(){
	  	$id = input('id');
	    $arr = Db::table('think_goods')->where('id','EQ',$id)->find();
		$cate_id = $arr['cate_id'];
		$goods_id = Db::table('think_goods_cate')->where('id','EQ',$cate_id)->where('status','EQ',1)->value('id');
		$goods_name = Db::table('think_goods_cate')->where('id','EQ',$cate_id)->where('status','EQ',1)->value('name');
		$goods_cate = Db::table('think_goods_cate')->where('status','EQ',1)->select();
		$this->assign('goods_id',$goods_id);
	    $this->assign('goods_cate',$goods_cate);
		$this->assign('goods_name',$goods_name);
		$this->assign('arr',$arr);
		return $this->fetch();
	  }

	  //修改的商品添加到数据库
	  public function update_seller_new(){
		//$arr = input();
		$arr = Request::instance()->post();
		$id = $arr['id'];
		$arr['end_time']=strtotime($arr['end_time']);
		$arr['xg_time']=time();
		$arr['status']=1;
		$res = Db::table('think_goods')->where('id','EQ',$id)->update($arr);
		if($res){
			$res_new['code'] = 1;
			$res_new['msg']='修改成功，请等待审核！';

		}else{
			$res_new['code'] = 0;
			$res_new['msg']='提交失败，请稍后重试！';
		}

		return $res_new;

	  }

	  //放单人我的商品//全部
	public function myGoods(){
		$id = input('id');
		if($id){
			  $arry = Db::table('think_goods')->where('id','EQ',$id)->paginate(5,false,['query'=>input()]);
	          $aggregate = $this->Summary();
		}else{
		      $date = Session::get('date');
			  $uid = $date['id'];
			  $zt_arr = Db::table('think_goods')->where('uid','EQ',$uid)->where('status','EQ',2)->field('end_time,id')->select();
			  foreach($zt_arr as $key=>$val){
			  	 if($val['end_time']<time()){
			  	 	$xj = Db::table('think_goods')->where('id','EQ',$val['id'])->update(['status'=>4]);
			  	 }
			  }
			  $arry = Db::table('think_goods')->where('uid','EQ',$uid)->paginate(5,false,['query'=>input()]);
			  $aggregate = $this->Summary();
	  }
	  $this->assign('aggregate',$aggregate);
	  $this->assign('arry',$arry);
      return $this->fetch();
    }

	//添加商品链接检查
	public function is_url(){
            $urls = input('urls');
	       //$urls = "https://detail.tmall.com/item.htm?id=578156996513";
			$arr = parse_url($urls);
			if(array_key_exists('scheme',$arr) && array_key_exists('query',$arr)){
				$arr_query = $this->convertUrlQuery($arr['query']);
			  if(array_key_exists('id',$arr_query))	{
				$id = $arr_query['id'];
	  			$ch = curl_init();
	     	    $url = "http://api.tkurl.top/itemInfo?appkey=VYnPTEkn&item_id=".$id;
				curl_setopt ($ch, CURLOPT_URL, $url);
				curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
				$dxycontent = curl_exec($ch);
				curl_close($ch);
				$data = json_decode ($dxycontent,true);
				if(array_key_exists('item_id',$data) && array_key_exists('item_url',$data)){
				 	$sp_id = Db::table('think_goods')->where('sp_id','EQ',$id)->where('status=1 || status=2')->find();
					 if(!count($sp_id)){
					 	Session::set('data',$data);
						$data['code']=1;
					    return $data;
					 }else{
					 	$data['code']=0;
						$data['msg']='该商品已在平台存在';
			            return $data;
					 }
				}else{
					   $data['code']=0;
						$data['msg']='请输入有效的商品链接地址';
			            return $data;
				}
			  }else{
			  	  $data['code']=0;
				  $data['msg']='请输入有效的商品链接地址';
			       return $data;
			  }
			}else{
				  $data['code']=0;
				  $data['msg']='请输入有效的商品链接地址';
			       return $data;
			}
	}


	//获取商品链接过来的参数
	public function convertUrlQuery($query){
		    $queryParts = explode('&', $query);
		    $params = array();
		    foreach ($queryParts as $param) {
		        $item = explode('=', $param);
		        $params[$item[0]] = $item[1];
		    }
		    return $params;
  }





    public function newgoods(){
       $id = input('id');
	   $url = Db::table('think_goods')->where('id','EQ',$id)->value('web_address');
       $this->assign('url',$url);
      return $this->fetch();
    }

	//商家添加商品渲染
	public function addseller(){
	  $zhiliao= Session::get('data');
	  $goods_cate = Db::table('think_goods_cate')->where('status','EQ',1)->field('name,id')->select();
	  $this->assign('goods_cate',$goods_cate);
	  $this->assign('zhiliao',$zhiliao);
       return $this->fetch();
    }

	//检测优惠劵链接地址
	public function is_url_add(){
	  $arr = input();
	  $sp_urls = $arr['sp_url'];
	  $yhj_urls = $arr['sp_yhj'];
	  $arr_sp_urls = parse_url($sp_urls);
	  $arr_yhj_urls  = parse_url($yhj_urls);
	  if(array_key_exists('scheme', $arr_yhj_urls) && array_key_exists('query', $arr_yhj_urls)){
		$arr_query_new = $this->convertUrlQuery($arr_yhj_urls['query']);
		$arr_query = $this->convertUrlQuery($arr_sp_urls['query']);
		$id = $arr_query['id'];
		if(array_key_exists('activityId',$arr_query_new)){
				$activityId = $arr_query_new['activityId'];
			// $url="http://api.tkurl.top/api/alimama/couponInfo?appkey=VYnPTEkn&item_id=58068156211&activity_id=f5555ff8eb30441e803c6d2b38f31e99 ";
			   $url="http://api.tkurl.top/api/alimama/couponInfo?appkey=VYnPTEkn&item_id=".$id."&activity_id=".$activityId;
			   $data_yhj = file_get_contents($url);
		       $datas =json_decode($data_yhj,true);
			   if(array_key_exists('tbk_coupon_get_response',$datas)){
			   	 $data=$datas['tbk_coupon_get_response']['data'];
				 return $data;
			   }else if(array_key_exists('error_response',$datas)){
			   	 $data=$datas['error_response'];
			     return $data;
			   }
		}else{
			 $data=[];
		     return $data;
		}
	}else{
		 $data=[];
	     return $data;
	 }

	}


	//商家添加的数组保存到数据库
	public function add_seller_new(){
		$date= Session::get('date');
		$uid = $date['id'];
//		$arr = input();
		$arr = Request::instance()->post();
		if($arr['sale_time']==''){
			$arr['sale_time']=time();
		}else{
		    $arr['sale_time'] = strtotime($arr['sale_time']);
		}
		$arr['end_time'] = strtotime($arr['end_time']);
		$arr['add_time']=time();
		$arr['uid']=$uid;
		$seller_id =Db::table('think_seller')->where('uid','EQ',$uid)->value('id');
		$arr['seller_id']=$seller_id;
		$res = Db::table('think_goods')->insert($arr);
		if($res){
			$res_new['code'] = 1;
			$res_new['msg']='提交成功，请等待审核！';

		}else{
			$res_new['code'] = 0;
			$res_new['msg']='提交失败，请稍后重试！';
		}

		return $res_new;
	}

	//判断用户是否是商家
	public function is_application(){
		$arr= Session::get('date');
		$mobile= $arr['mobile'];
		$array=Db::table('think_user')->where('mobile','EQ',$mobile)->field('user_type_id')->find();
		if($array['user_type_id']==3){
		return $str = 'seller/index';
		}
	}

	//放单申请
	public function application(){
		$str =  $this->is_application();
		if($str){
			$aggregate = $this->Summary();
	        $this->assign('aggregate',$aggregate);
			return $this->fetch($str);
		}else{
			return $this->fetch();
		}

    }
	//放单申请资料
	public function materials(){
	    $str =  $this->is_application();
			if($str){
				return $this->fetch($str);
			}else{
				return $this->fetch();
			}

	}

	//放单资料申请提交
	public function materials_add(){
     $str =  $this->is_application();
		if($str){
			return $this->fetch($str);
		}else{
			$data_new = Request::instance()->post();
			$identity=$data_new['identity'];
			$qq=$data_new['qq'];
			$mobile=$data_new['mobile'];

			//身份证正则表达式(15位)
			$isIDCard1 = preg_match('/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/', $identity, $matches);
			//身份证正则表达式(18位)
			$isIDCard2 = preg_match('/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/', $identity, $matches);
			//qq正则表达式
			$isqq= preg_match('/^[1-9][0-9]{4,14}$/', $qq, $matches);
			/*echo $isqq;exit;*/
			//手机号正则表达式
			$isMatched = preg_match('/^0?(13|14|15|17|18)[0-9]{9}$/', $mobile, $matches);
				if($isIDCard1 || $isIDCard2){
				  if($isqq){
				  	 if($isMatched){
				  	 	 $arr= Session::get('date');
						 $data_new['uid'] = $arr['id'];
				  	 	 $data_new ['add_time']= time();
				  	 	 $re = Db::table('think_seller')->insert($data_new);
						 if($re){
						 	$data['code'] = 2;
					        $data['msg']='提交成功';
					        return $data;
						 }else{
						 	$data['code'] = 1;
					        $data['msg']='提交失败';
					        return $data;
						 }
				  	 }else{
				  	 	$data['code'] = 1;
					    $data['msg']='请输入正确的手机号';
					    return $data;
				  	 }
				  }else{
				  	$data['code'] = 1;
					$data['msg']='请输入正确的QQ号';
					return $data;
				  }
				}else{
				    $data['code'] = 1;
					$data['msg']='请输入正确的身份证号码';
					return $data;
				}
			return $data;
		}

    }

  //用户反馈
   public function feedback(){
	   	$arr= Session::get('date');
		$id =$arr['id'];
		$array = Db::table('think_review')->alias('a')->join('think_user b','a.uid = b.id','RIGHT')->join('think_goods c','a.sp_id = c.id')->where('a.f_id','EQ',$id)->where('a.status','EQ',1)->field('b.mobile,a.content,a.time,c.title,c.large_img,c.id,a.id,a.reply,c.sp_id,c.web_address')->paginate(5,false,['query'=>input()]);
		/*echo '<pre>';
		print_r($arr);exit;*/
		$this->assign('array',$array);
		return $this->fetch();
   }

    //商家回复
    public function reply(){
	    $arr = input();
		$id = $arr['id'];
		$data['reply'] = $arr['reply'];
		$data['reply_time'] = time();
		$res = Db::table('think_review')->where('id','EQ',$id)->update($data);
		if($res){
		$reply = Db::table('think_review')->where('id','EQ',$id)->value('reply');
			$date['code']=1;
			$date['msg']=$reply;
		}else{
			$date['code']=2;
			$date['msg']='系统忙，稍后再试';
		}
		return $date;
    }


     //系统消息
    public function message(){
   	 	$arr= Session::get('date');
		$id =$arr['id'];
//		$arr = Db::table('think_goods')->alias('a')->join('think_system_message b','a.id = b.relate_id' )->where('a.uid','EQ',$id)->where('b.uid','NEQ',-2)->field('b.admin_id,b.content,b.add_time,b.type,a.id')->paginate(10,false,['query'=>input()]);
		$where = [-1,0,$id];
	   	$messages = Db::name('system_message')->where('uid','in',implode(',',$where))->paginate(10,false,['query'=>input()]);
//		dump($messages);die;
		foreach($messages as $k=>$v){
			if($v['type'] == 1){
				$message = Db::name('goods')->where('id',$v['relate_id'])->value('title');
				$v['message'] = '"'.$message.'"【'.$v['content'].'】';
			}else if($v['type'] == 2){
				$v['message'] = '您于'.date('Y-m-d H:i:s',$v['add_time']).'的充值信息于实际充值信息不符';
			}else{
				$v['message'] = $v['content'];
			}
			$messages[$k] = $v;
		}
	    //dump($messages);die;
		//$this->assign('arr',$arr);
		$this->assign('messages',$messages);
	    return $this->fetch();
   }
	
	//系统消息详情
	public function messageDetails(){
	$id = input('id');
	$arr = Db::name('system_message')->where('id','EQ',$id)->find();
	$this->assign('arr',$arr);
	return $this->fetch();	
	}

  	/**
		 *放单中心结算
		*/
	  public function balance(){
				$param = Request::instance()->param();
				$sellerService = new SellerService;
				$data = $sellerService->balance($param);
				// dump($data);die;
				$this->assign('data',$data);
	  		return $this->fetch();
	  }

	  /**
		 *打款页面
		*/
	  public function make(){
				if(Request::instance()->isGet()){
						return $this->fetch();
				}else{
						$sellerService = new SellerService;
						$post = Request::instance()->post();
						return json($sellerService->makePost($post));
				}
	  }

		/**
		 * 上传打款截图
		*/
		public function upload()
		{
				$file = request()->file('file');
				// 移动到框架应用根目录/public/uploads/ 目录下
				if($file){
						$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
						if($info){
								return json(['code'=>1,'msg'=>'上传成功','data'=>array('src'=>'/uploads/'.$info->getSaveName())]);
						}else{
								return json(['code'=>-1,'msg'=>$file->getError()]);
						}
				}
		}
}
